var util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
//获取应用实例
const app = getApp();
var that;
Page({
  data: {
    mobile: '',
    isSendVerifiCode: false,
    isNeedBack:false, //是否需要回退页面
    code:'',
    jumpPage: '',
    needJump: false,
  },
  onLoad: function (options) {
    that = this;
    if(typeof options.phone !='undefined') {
      this.setData({ mobile: options.phone});
    }
    if (typeof options.isNeedBack != 'undefined') {
      this.setData({ isNeedBack: true });
    }
    //图形验证码缓存key
    let captchaKey = util.generateUUID();
    that.setData({ captcha: api.GetCaptcha + '/' + captchaKey + '&' + new Date().getTime(), captchaKey: captchaKey });
    if (options.page) {
      that.setData({
        jumpPage: decodeURIComponent(options.page),
        needJump: true
      });
    }
  },
  onShow(){
    that.refreshCode();
  },
  refreshCode: function () {
    util.login().then((res) => {
      that.setData({
        code: res.code
      });
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  // 下一步
  toNextStep: function () {
    wx.showLoading({
      title: '验证码校验中',
    })
    app.postPureForm(api.VerifyCode, { mobile: that.data.mobile, verifyValue: that.data.verifyValue, captchaKey:that.data.captchaKey,isAllow:true}).then(rsp => {
      wx.hideLoading();
      that.onSendSMS();
    });
  },
  // 倒计时，发送短信验证码
  onSendSMS: function () {
    app.postPureForm(api.sendVerifiCodeForReg, { phone: that.data.mobile, isAllow: true},{retry:3}).then(rsp => {
      //短信验证码缓存key
      let captchaKey = rsp.captchaKey;
      that.setData({
        isHidden: true,
        smsCaptchaKey: captchaKey
      });
      that.setData({ time: 60 });
      var timer = setInterval(function () {
        that.setData({
          time: --that.data.time
        });
        if (1 > that.data.time) {
          clearInterval(timer);
        }
      }, 1000);
    }).catch((err) => {
      console.log('err', err);
    });
  },
  // 完成提交
  submit: function () {
    if (!that.data.smsVerifyCode){
      return wx.showToast({
        title: '短信验证码必填',
        icon: 'none',
        duration: 1500
      });
    }
    app.post(api.BindPhone, { mobile: that.data.mobile, smsVerifyCode: that.data.smsVerifyCode, smsCaptchaKey: that.data.smsCaptchaKey, code: that.data.code, isAllow: true }).then(rsp => {
      var res = rsp.data;
      if (res){
        //实名是否认证成功
        app.globalData.isCert = res.isCert;
        wx.setStorageSync('isCert', res.isCert);
        wx.setStorageSync('isTouristRent', res.isTouristRent);
        app.isTouristRent = res.isTouristRent;
        wx.setStorageSync('phoneNumber', res.phoneNumber);
        wx.setStorageSync('tenantNo', res.tenantNo);
        wx.setStorageSync('token', res.token);
        app.globalData.phoneNumber = res.phoneNumber;
        app.globalData.tenantNo = res.tenantNo;
        app.globalData.hasLogin = true;
        if (that.data.isNeedBack){ //来自于页面检查跳转
          wx.navigateBack({
            delta:1
          })
          return true;
        }
        if (that.data.needJump && that.data.jumpPage.indexOf('pages/index/index') == -1) {
          wx.redirectTo({
            url: '/' + that.data.jumpPage,
          })
        } else {
          //console.log('pages', getCurrentPages());
          var p = getCurrentPages()[0];
          if (!p.data.isUpdate) {
            p.setData({ isUpdate: true });
          }
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }
    });
  },
  // 把输入的手机号码存到全局data里
  bindPhoneInput: function (e) {
    that.setData({ mobile: e.detail.value });
    that.change();
  },
  // 把输入的图形验证码存到全局data里
  bindVerifyInput: function (e) {
    that.setData({ verifyValue: e.detail.value });
    that.change();
  },
  change: function(){
    var mobile = that.data.mobile;
    var verifyValue = that.data.verifyValue
    if ((mobile && util.isValidPhone(mobile)) && (verifyValue && 5 === verifyValue.length)){
      that.setData({ change: true })
    }else{
      that.setData({ change: false })
    }
  },
  // 输入短信验证码
  bindVerifyCode: function (e) {
    this.setData({
      smsVerifyCode: e.detail.value
    });
  },
  // 刷新验证码
  onRefresh: function () {
    this.setData({ captcha: api.GetCaptcha + '/' + this.data.captchaKey + '&' + new Date().getTime() });

  },
  // 清空手机号码
  clearPhoneNumber: function () {
    this.setData({
      mobile: '',
      change: false
    });
  },
})